package com.yc.started.login.web;

import com.yc.started.login.LoginProperties;
import com.yc.started.login.biz.AuthBiz;
import com.yc.started.login.biz.BizException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("auth")
public class LoginAction {

    @Autowired
    LoginProperties loginProperties;

    @RequestMapping("props")
    public LoginProperties properties(){
        return loginProperties;
    }

    @Autowired
    AuthBiz authBiz;

    @RequestMapping("login")
    Object login(String username, String password,
                 HttpSession session) throws BizException {
        try{
            Object ret = authBiz.login(username, password);
            // 登录成功, 保存用户对象到会话
            session.setAttribute(loginProperties.getSessionKey(),
                    ret);
            return Map.of("msg","登录成功",
                    "code", 1,
                    "data", ret);
        }catch (BizException e){
            return Map.of("msg",e.getMessage(),
                    "code", 0);
        }
    }

    @RequestMapping("myinfo")
    public Object myinfo(HttpSession session){
        Object ret = session.getAttribute(loginProperties.getSessionKey());
        if(ret == null){
            return Map.of("msg","未登录",
                    "code", 0);
        }
        return Map.of("msg","查询成功",
                "code", 1,
                "data", ret);
    }

    @RequestMapping("logout")
    public Object logout(HttpSession session){
        session.invalidate();
        return Map.of("msg","退出成功",
                "code", 1);
    }
}
